<template>
  <a-select :placeholder="placeholder"
            :allowClean="allowClean"
            :disabled="disabled" defaultValue="" :value="stateValue" @change="handleInput">
    <a-select-option value="">请选择</a-select-option>
    <a-select-option v-for="(item, key) in dictOptions" :key="key" :value="item.value">
      <span style="display: inline-block;width: 100%" :title=" item.text || item.label ">
        {{ item.text || item.label }}
      </span>
    </a-select-option>
  </a-select>
</template>

<script>
  import {getAction} from '../../api/manage';
  import {sysDictUrl} from '../../api/url'

  // 字典下拉单选框
  export default {
    name: "AkDictSelectTag",
    props: {
      dictCode: String,
      placeholder: String,
      allowClean:{
        type: Boolean,
        required:false,
        default:true
      },
      defaultFirst:{
        type:Boolean,
        required:false,
        default:false,
      },
      value:{
        type: String,
        required: false
      },
      disabled:{
        type:Boolean,
        required:false,
        default:false,
      }
    },
    data() {
      return {
        dictOptions: [],
        stateValue:''
      }
    },
    created() {
      //获取字典数据
      this.initDictData();
      this.stateValue = this.value;
    },
    mounted(){

    },
    methods: {
      initDictData() {
        //根据字典Code, 初始化字典数组
        let  url = sysDictUrl.getDictItems+this.dictCode

        getAction(url).then((res) => {
          if (res.success) {
            this.dictOptions = res.result;
            if(this.defaultFirst && !this.stateValue){
              this.stateValue=(this.dictOptions[1]||{}).value;
              this.handleInput(this.stateValue);
            }
          }else {
            this.dictOptions = [{key:"", value:"", title:"请选择"}]
          }
        })
      },
      handleInput(e) {
        this.$emit('change', e);
        let label = undefined;
        if(e){
          let filter = this.dictOptions.filter(t=>t.value==e);
          if(filter.length>0){
            label = filter[0].text || filter[0].label;
          }
        }
        this.stateValue=e;
        this.$emit('selected',e,label)
      },
    },
    model: {
      prop: 'value',
      event: 'change'
    },
    watch:{
      value: function value(val) {
        this.stateValue = val;
      }
    }
  }
</script>

<style scoped>
</style>
